<template>
  <view class="page">
    <canvas type="2d" id="canvas" canvas-id="canvas"></canvas>
    <view class="back-btn" @tap="goBack">
      <text class="iconfont icon-back">返回</text>
    </view>
  </view>
</template>

<script>
class Particle {
  constructor(x, y, color) {
    this.x = x;
    this.y = y;
    this.color = color;
    
    // 设置放射状运动
    const angle = Math.random() * Math.PI * 2;
    const speed = 2 + Math.random() * 3;
    this.velocity = {
      x: Math.cos(angle) * speed,
      y: Math.sin(angle) * speed
    };
    
    // 粒子属性
    this.alpha = 1;
    this.decay = 0.015;
    this.gravity = 0.05;
    this.size = 2;
    this.rays = []; // 存储射线点
    this.rayLength = 15 + Math.random() * 10; // 射线长度
  }

  update() {
    // 更新速度和位置
    this.velocity.y += this.gravity;
    this.x += this.velocity.x;
    this.y += this.velocity.y;
    
    // 存储射线点
    this.rays.unshift({ x: this.x, y: this.y });
    if (this.rays.length > 5) {
      this.rays.pop();
    }
    
    // 更新透明度
    this.alpha -= this.decay;
    return this.alpha > 0;
  }

  draw(ctx) {
    // 绘制射线效果
    if (this.rays.length > 1) {
      ctx.beginPath();
      ctx.moveTo(this.rays[0].x, this.rays[0].y);
      for (let i = 1; i < this.rays.length; i++) {
        ctx.lineTo(this.rays[i].x, this.rays[i].y);
      }
      ctx.strokeStyle = `rgba(${this.color}, ${this.alpha})`;
      ctx.lineWidth = this.size;
      ctx.stroke();
    }
  }
}

class Firework {
  constructor(x, y, targetX, targetY, color) {
    this.x = x;
    this.y = y;
    this.startX = x;
    this.startY = y;
    this.targetX = targetX;
    this.targetY = targetY;
    this.color = color;
    this.trail = [];
    
    const angle = Math.atan2(targetY - y, targetX - x);
    const speed = 15;
    this.velocity = {
      x: Math.cos(angle) * speed,
      y: Math.sin(angle) * speed
    };
  }

  update() {
    // 更新位置
    this.x += this.velocity.x;
    this.y += this.velocity.y;
    
    // 存储轨迹
    this.trail.unshift({ x: this.x, y: this.y });
    if (this.trail.length > 3) {
      this.trail.pop();
    }

    // 检查是否到达目标位置
    const distance = Math.hypot(this.targetX - this.x, this.targetY - this.y);
    return distance < 5;
  }

  draw(ctx) {
    // 绘制轨迹
    if (this.trail.length > 1) {
      ctx.beginPath();
      ctx.moveTo(this.trail[0].x, this.trail[0].y);
      for (let i = 1; i < this.trail.length; i++) {
        ctx.lineTo(this.trail[i].x, this.trail[i].y);
      }
      ctx.strokeStyle = `rgba(${this.color}, 1)`;
      ctx.lineWidth = 2;
      ctx.stroke();
    }
  }

  explode() {
    const particles = [];
    const particleCount = 80;
    for (let i = 0; i < particleCount; i++) {
      particles.push(new Particle(this.x, this.y, this.color));
    }
    return particles;
  }
}

export default {
  data() {
    return {
      canvas: null,
      ctx: null,
      width: 0,
      height: 0,
      fireworks: [],
      particles: [],
      timer: null,
      maxFireworks: 4,
      burstInterval: 1000,
      lastBurstTime: 0,
      colors: [
        '255, 200, 0',   // 金色
        '255, 150, 0',   // 橙色
        '150, 255, 0',   // 黄绿色
        '255, 100, 255'  // 粉色
      ],
      targetArea: {
        top: 0.2,      // 爆炸区域顶部（屏幕20%处）
        bottom: 0.4,   // 爆炸区域底部（屏幕40%处）
        padding: 0.2   // 水平边距（屏幕20%）
      }
    };
  },

  async onReady() {
    const sysInfo = uni.getSystemInfoSync();
    this.width = sysInfo.windowWidth;
    this.height = sysInfo.windowHeight;
    await this.initCanvas();
  },

  methods: {
    async initCanvas() {
      const query = uni.createSelectorQuery().in(this);
      await new Promise(resolve => {
        query.select('#canvas')
          .fields({ node: true, size: true })
          .exec((res) => {
            const canvas = res[0].node;
            this.canvas = canvas;
            this.ctx = canvas.getContext('2d');
            canvas.width = this.width;
            canvas.height = this.height;
            resolve();
          });
      });
      this.startAnimation();
    },

    createFirework() {
      const startX = this.width * (0.3 + Math.random() * 0.4);
      const startY = this.height;

      const targetTop = this.height * this.targetArea.top;
      const targetBottom = this.height * this.targetArea.bottom;
      const targetLeft = this.width * this.targetArea.padding;
      const targetRight = this.width * (1 - this.targetArea.padding);

      const targetX = targetLeft + Math.random() * (targetRight - targetLeft);
      const targetY = targetTop + Math.random() * (targetBottom - targetTop);

      const color = this.colors[Math.floor(Math.random() * this.colors.length)];
      return new Firework(startX, startY, targetX, targetY, color);
    },

    startAnimation() {
      this.timer = setInterval(() => {
        this.ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
        this.ctx.fillRect(0, 0, this.width, this.height);

        const currentTime = Date.now();
        if (currentTime - this.lastBurstTime >= this.burstInterval) {
          const burstCount = 2 + Math.floor(Math.random() * 2); // 2-3个烟花
          for (let i = 0; i < burstCount; i++) {
            setTimeout(() => {
              this.fireworks.push(this.createFirework());
            }, i * 200); // 间隔200ms发射
          }
          this.lastBurstTime = currentTime;
        }

        // 更新和绘制烟花
        for (let i = this.fireworks.length - 1; i >= 0; i--) {
          const firework = this.fireworks[i];
          firework.draw(this.ctx);
          if (firework.update()) {
            this.particles.push(...firework.explode());
            this.fireworks.splice(i, 1);
          }
        }

        // 更新和绘制粒子
        for (let i = this.particles.length - 1; i >= 0; i--) {
          const particle = this.particles[i];
          particle.draw(this.ctx);
          if (!particle.update()) {
            this.particles.splice(i, 1);
          }
        }
      }, 1000 / 60);
    },

    goBack() {
      if (this.timer) {
        clearInterval(this.timer);
      }
      uni.navigateBack();
    }
  }
};
</script>

<style>
page {
  background: #000;
}

.page {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  position: relative;
}

canvas {
  position: absolute;
  left: 0;
  top: 0;
  width: 100% !important;
  height: 100% !important;
}

.back-btn {
  position: fixed;
  top: 40px;
  right: 20px;
  z-index: 999;
  background: rgba(255, 255, 255, 0.2);
  padding: 8px 15px;
  border-radius: 20px;
  backdrop-filter: blur(5px);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}

.back-btn text {
  color: #fff;
  font-size: 16px;
}
</style>
